import React, {useState} from 'react';
import {
  Systrace,
  ScrollView,
  Pressable,
  StyleSheet,
  Text,
  View,
  Image,
  // DeviceEventEmitter,
  // Alert,
} from 'react-native';

// interface Scenario {
//   count: number;
//   elementType: string;
// }

// let drawnTss: number[] = []; // timestamps of when this component's native draw event fired

// DeviceEventEmitter.addListener('benchmarkComponentDrawn', e => {
//   Systrace.beginEvent('benchmarkComponentDrawn');
//   // TODO: performance.now only have ms level accuracy, no decimals, sub ms accuracy solutions?
//   drawnTss.push(performance.now());
//   Systrace.endEvent();
// });

function MeasureComponent(props: {
  children: React.ReactNode;
  title: string;
  startTime: number;
}): JSX.Element {
  // // alert test result
  // setTimeout(() => {
  //   let took = (drawnTss[1] - props.startTime).toFixed(3);
  //   Systrace.beginEvent(`benchmarkAlerting: ${took}`);
  //   drawnTss.sort();
  //   Alert.alert(props.title, took + ' ms', [{text: 'OK'}]);
  //   drawnTss = [];
  //   Systrace.endEvent();
  // }, 1500);

  return (
    <>
      <View
        style={{margin: 10, height: 5, width: '100%', backgroundColor: 'black'}}
        // nativeID={'rnohBenchmarkComponentId'}
      />
      {props.children}
    </>
  );
}

function Button(props: {
  onPress: (timestamp: number) => void;
  title: string;
}): JSX.Element {
  return (
    <Pressable
      style={styles.button}
      onPress={event => {
        props.onPress(event.nativeEvent.timestamp);
      }}>
      <Text numberOfLines={2} style={styles.text}>
        {props.title}
      </Text>
    </Pressable>
  );
}

function ViewTest(props: {count: number}): JSX.Element {
  return (
    <MeasureComponent
      title={`${props.count} <View />`}
      // startTime={performance.now()}
    >
      {Array.from(Array(props.count).keys()).map((value, index) => (
        <View
          key={index}
          style={{
            width: 100,
            height: 100,
            backgroundColor: 'red',
            margin: 5,
          }}
        />
      ))}
    </MeasureComponent>
  );
}

function TextTest(props: {count: number}): JSX.Element {
  return (
    <MeasureComponent
      title={`${props.count} <Text />`}
      // startTime={performance.now()}>
    >
      {Array.from(Array(props.count).keys()).map((value, index) => (
        <Text key={index}>Nice text: {index}</Text>
      ))}
    </MeasureComponent>
  );
}

function ImageTest(props: {count: number}): JSX.Element {
  return (
    <MeasureComponent
      title={`${props.count} Image`}
      // startTime={performance.now()}
    >
      {Array.from(Array(props.count).keys()).map((value, index) => (
        <Image
          style={{width: 100, height: 100, margin: 5}}
          source={{
            uri: 'https://res6.vmallres.com/pimages/uomcdn/CN/pms/202309/gbom/6942103109584/800_800_D5053BB8A6FECB4906EC5869E78CEEC5mp.png',
          }}
        />
      ))}
    </MeasureComponent>
  );
}

const elementTypes: string[] = ['View', 'Text', 'Image'];
const counts: number[] = [1500, 5000];
const getTestCaseTitle = (count: number, elementType: string) =>
  `Render ${count} <${elementType} />`;

export default function Benchmark() {
  const [scenario, setScenario] = useState<string | null>(null);

  let perfTest = null;
  if (scenario != null) {
    switch (scenario) {
      case 'View':
        perfTest = <ViewTest count={1500} />;
        break;
      case 'Text':
        perfTest = <TextTest count={1500} />;
        break;
      case 'Image':
        perfTest = <ImageTest count={1500} />;
        break;
    }
  }

  return (
    <ScrollView
      contentContainerStyle={{alignItems: 'center'}}
      automaticallyAdjustContentInsets={true}
      removeClippedSubbiews={true}>
      {scenario === null
        ? elementTypes.map(elementType =>
            counts.map(count => (
              <Button
                onPress={timestamp => {
                  // Systrace.beginEvent('start_test');
                  setScenario(elementType);
                  // Systrace.endEvent();
                }}
                title={getTestCaseTitle(count, elementType)}
              />
            )),
          )
        : null}
      {scenario != null ? (
        <>
          <Button
            onPress={() => {
              setScenario(null);
            }}
            title="Reset"
          />
          {perfTest}
        </>
      ) : null}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  button: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    paddingHorizontal: 32,
    borderRadius: 15,
    backgroundColor: 'grey',
    flex: 1,
    margin: 10,
  },
  text: {
    fontSize: 16,
    lineHeight: 20,
    fontWeight: 'bold',
    letterSpacing: 0.25,
    color: 'white',
  },
});
